package com.chuangdun.flutter.plugin.alarm

import android.app.AlarmManager
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import java.util.Calendar

/**
 * 闹钟恢复服务
 * 用于在设备启动后恢复数据库中的闹钟设置
 */
class AlarmRestoreService : IntentService("AlarmRestoreService") {

    companion object {
        const val ACTION_RESTORE_ALARMS = "com.chuangdun.flutter.alarm.RESTORE_ALARMS"
    }

    override fun onHandleIntent(intent: Intent?) {
        when (intent?.action) {
            ACTION_RESTORE_ALARMS -> {
                Log.d(TAG, "开始执行闹钟恢复任务")
                restoreAllAlarms(this)
            }
        }
    }

    /**
     * 恢复所有闹钟
     */
    private fun restoreAllAlarms(context: Context) {
        val startTime = System.currentTimeMillis()
        
        try {
            Log.d(TAG, "开始恢复闹钟数据")
            
            val databaseHelper = AlarmDatabaseHelper(context)
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val allAlarms = databaseHelper.getAllAlarms()
            
            Log.d(TAG, "从数据库获取到 ${allAlarms.size} 个闹钟")
            
            var restoredCount = 0
            var skipCount = 0
            var errorCount = 0
            
            for (alarmModel in allAlarms) {
                try {
                    if (alarmModel.repeating) {
                        // 重复闹钟：设置下一次触发时间
                        restoreRepeatingAlarm(context, alarmManager, alarmModel)
                        restoredCount++
                    } else {
                        // 一次性闹钟：检查时间是否已过
                        if (restoreOneTimeAlarm(context, alarmManager, alarmModel)) {
                            restoredCount++
                        } else {
                            skipCount++
                        }
                    }
                } catch (e: Exception) {
                    errorCount++
                    Log.e(TAG, "恢复闹钟失败: ${alarmModel.alarmId}, 错误: ${e.message}")
                }
            }
            
            val duration = System.currentTimeMillis() - startTime
            Log.d(TAG, "闹钟恢复完成: 总数=${allAlarms.size}, 成功=$restoredCount, 跳过=$skipCount, 失败=$errorCount, 耗时=${duration}ms")
            
        } catch (e: Exception) {
            Log.e(TAG, "恢复闹钟时发生错误: ${e.message}")
        }
    }

    /**
     * 恢复重复闹钟
     * 计算距离当前时间最近的未来触发时间点，以增强闹钟恢复的健壮性。
     */
    private fun restoreRepeatingAlarm(
        context: Context,
        alarmManager: AlarmManager,
        alarmModel: AlarmModel
    ) {
        val now = System.currentTimeMillis()
        val calendar = Calendar.getInstance()
        // 设置为今天指定的时间
        calendar.set(Calendar.HOUR_OF_DAY, alarmModel.hour)
        calendar.set(Calendar.MINUTE, alarmModel.minute)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)

        // 如果今天的时间已过，则移动到明天
        while (calendar.timeInMillis <= now) {
            calendar.add(Calendar.DAY_OF_MONTH, 1)
        }

        setAlarm(context, alarmManager, alarmModel, calendar.timeInMillis)
        Log.d(TAG, "恢复重复闹钟: ${alarmModel.alarmId}, 下次触发时间: ${calendar.time}")
    }

    /**
     * 恢复一次性闹钟
     * @return true 如果闹钟被成功恢复, false 如果时间已过被跳过
     */
    private fun restoreOneTimeAlarm(
        context: Context,
        alarmManager: AlarmManager,
        alarmModel: AlarmModel
    ): Boolean {
        if (alarmModel.date == null) {
            Log.w(TAG, "一次性闹钟日期为空，跳过: ${alarmModel.alarmId}")
            return false
        }

        // 使用 DateUtils 解析日期和构建完整时间
        val calendar = DateUtils.buildDateTime(alarmModel.date, alarmModel.hour, alarmModel.minute)
        if (calendar == null) {
            Log.w(TAG, "日期解析失败，跳过闹钟: ${alarmModel.alarmId}, 日期: ${alarmModel.date}")
            return false
        }

        // 检查时间是否已过
        if (calendar.timeInMillis <= System.currentTimeMillis()) {
            Log.d(TAG, "一次性闹钟时间已过，跳过: ${alarmModel.alarmId}, 时间: ${calendar.time}")
            return false
        }

        setAlarm(context, alarmManager, alarmModel, calendar.timeInMillis)
        Log.d(TAG, "恢复一次性闹钟: ${alarmModel.alarmId}, 触发时间: ${calendar.time}")
        return true
    }

    /**
     * 设置闹钟
     */
    private fun setAlarm(
        context: Context,
        alarmManager: AlarmManager,
        alarmModel: AlarmModel,
        triggerTime: Long
    ) {
        val intent = AlarmReceiver.createAlarmIntent(
            context,
            alarmModel.tag,
            alarmModel.alarmId,
            alarmModel.title,
            alarmModel.body,
            alarmModel.repeating
        )
        
        val requestCode = AlarmReceiver.getRequestCode(alarmModel.tag, alarmModel.alarmId)
        val pendingIntent = AlarmReceiver.createBroadcastPendingIntent(context, requestCode, intent)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                triggerTime,
                pendingIntent
            )
        } else {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "闹钟恢复服务已销毁")
    }
}